<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="分类名字">
          <el-input v-model="form.categoryName" placeholder="请输入用户名称"/>
        </el-form-item>
        <el-form-item label="排序权重">
          <el-input-number v-model="form.categoryPosition" :min="0" label="排序权重"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSubmit">立即保存</el-button>
          <el-button size="small" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { createCategory, getCategoryDetail, updateCategory } from '@/api/Category'

export default {
  data() {
    return {
      form: {
        categoryId: '',
        categoryName: '',
        categoryPosition: ''
      }
    }
  },
  created() {
    if (this.$route.query.categoryId) {
      this.form.categoryId = this.$route.query.categoryId
      this.getCategory()
    }
  },
  methods: {
    cancel() {
      this.$router.push('/category/list')
    },
    getCategory() {
      getCategoryDetail({ id: this.form.categoryId }).then(res => {
        if (res.code === 200) {
          this.form.categoryId = res.data.categoryId
          this.form.categoryName = res.data.categoryName
          this.form.categoryPosition = res.data.categoryPosition
        } else {
          this.$message.error('网络错误')
        }
      })
    },
    onSubmit() {
      const form = {
        categoryId: this.form.categoryId,
        categoryName: this.form.categoryName,
        categoryPosition: this.form.categoryPosition,
        parentId: 0,
        categoryLevel: 0,
        categoryStatus: 0
      }
      if (form.categoryId) {
        updateCategory(form).then(res => {
          if (res.code === 200) {
            this.$message.success('保存成功')
            this.$router.push('/category/list')
          } else {
            this.$message.error('网络错误')
          }
        })
      } else {
        createCategory(form).then(res => {
          if (res.code === 200) {
            this.$message.success('保存成功')
            this.$router.push('/category/list')
          } else {
            this.$message.error('网络错误')
          }
        })
      }
    }
  }
}
</script>
